package com.tanhua.sso.controller;

import com.tanhua.sso.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;


    //验证码校验
    @PostMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String, String> params){
        try {
            String phone = params.get("phone");
            String code = params.get("verificationCode");

            //调用方法userService.login
            String data=userService.login(phone,code);

            //1.若data不为空，则验证码和手机号都正常
            if(StringUtils.isNotBlank(data)){
                //登入成功
                Map<String, Object> result=new HashMap<>(2);

                String[] splits = StringUtils.split(data, "|");
                result.put("token",splits[0]);
//                result.put("isNew",splits[1]);

                result.put("isNew",splits[1].equals("true")?true:false);

//                result.put("isNew",false);
//                return ResponseEntity.ok(result);
                return ResponseEntity.ok().body(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //2,data为空，验证码有问题
        ErrorResult errorResult = ErrorResult.builder().errCode("0000002").errMessage("登入失败,验证码有误").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);

    }

    /**
     * 校验token，根据token查询用户数据
     *
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.userService.queryUserByToken(token);
    }
}
